﻿using System;
using Gp.Scripts.Core;
using Sirenix.OdinInspector;
using UnityEditor;
using UnityEngine;

namespace Gp.Scripts.Editor
{
    [Serializable]
    public class CameraPivotNode
    {
        
        private SettleEditor _settleEditor;
        
        private CameraFlowPivot _flowPivot;
        private UnityEditor.Editor _editor;
        
        public CameraPivotNode(SettleEditor settleEditor)
        {
            _settleEditor = settleEditor;
        }


        private void TryInit()
        {
            if (_flowPivot) return;
            if (!Application.isPlaying) return;
            _flowPivot = Global.GetSceneRoot<PlayerRoot>().CameraFlowPivot;
            if (!_flowPivot) return;
            _editor = UnityEditor.Editor.CreateEditor(_flowPivot);
        }

        [OnInspectorInit]
        private void OnInspectorInit()
        {
            TryInit();
        }
        
        [OnInspectorGUI]
        private void OnInspectorGUI()
        {
            if (!_editor || !_editor.serializedObject.targetObject)
            {
                GUILayout.Space(20);
                GUILayout.Label("游戏尚未运行...");
                return;
            }
            _editor.OnInspectorGUI();
            if (GUILayout.Button(new GUIContent("保存")))
            {
                Save();
            }
        }
        
        
        private void Save()
        {
            if (!_flowPivot) return;
            var prefabCom = AssetDatabase.LoadAssetAtPath<CameraFlowPivot>(PathConst.CAMERA_FOLLOW_PIVOT);
            if (!prefabCom)
            {
                _settleEditor.ShowNotification(new GUIContent($"组件丢失，路径: {PathConst.CAMERA_FOLLOW_PIVOT}"));
                return;
            }
            
            UnityEditorInternal.ComponentUtility.CopyComponent(_flowPivot);
            UnityEditorInternal.ComponentUtility.PasteComponentValues(prefabCom);
            EditorUtility.SetDirty(prefabCom.gameObject);
        }
    }
}